﻿using Elasticsearch.Net;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Nest;
using System;
using System.Linq;
using Micro.Extensions.Utilities;

namespace Micro.Srv.LogCenter
{
    public class ElasticClientHelper
    {
        private readonly ElasticClient _client;

        public ElasticClientHelper(IOptions<ElasticSearchOptions> options, ILogger<ElasticClientHelper> logger)
        {
            var uris = options.Value.Hosts.Split(',').Select(s => new Uri(s)).ToArray();
            ConnectionSettings settings = null;
            if (uris.Length == 1)
            {
                settings = new ConnectionSettings(uris[0]);
            }
            else
            {
                settings = new ConnectionSettings(new SniffingConnectionPool(uris));
            }

            settings.PingTimeout(TimeSpan.FromSeconds(30))
            .RequestTimeout(TimeSpan.FromSeconds(30))
            .DefaultFieldNameInferrer((name) => name);//字段名称不变，默认首字母小写

            settings.BasicAuthentication(options.Value.UserName, options.Value.Password); //设置账号密码，没有可以跳过
            _client = new ElasticClient(settings);

            logger.LogDebug("初始化 ElasticSearch，配置信息为：{0}", options.Value.ToJson());
        }

        public ElasticClient ElasticClient => _client;
    }
}
